<template>
  <div class="app-container">
    <el-form class="formList"
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
      size="small">
      <el-row>


        <el-form-item label="手机号码"
          prop="phone">
          <el-input v-model="queryParams.phone"
            placeholder="请输入手机号码"
            clearable
            size="small"
            style="width: 232px;"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="用户名称"
          prop="customerName">
          <el-input v-model="queryParams.customerName"
            placeholder="请输入用户名称"
            clearable
            size="small"
            style="width: 232px;"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="状态"
          prop="status">
          <el-select v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            size="small"
            style="width: 232px;">
            <el-option v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>


      </el-row>
      <el-row>
        <el-form-item label="会员等级"
          prop="levelUid">
          <el-select v-model="queryParams.levelUid"
            placeholder="请选择"
            clearable
            style="width: 232px;"
            @keyup.enter.native="handleQuery">
            <el-option v-for="item in LevelInfoArr"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间"
          prop="createTimeArr">
          <el-date-picker v-model="queryParams.createTimeArr"
            type="daterange"
            align="right"
            value-format="yyyy-MM-dd"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 232px;"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会员身份"
          prop="status">
          <el-select v-model="queryParams.customerType"
            placeholder="请选择会员身份"
            clearable
            size="small"
            style="width: 232px;">
            <el-option v-for="dict in sfOptions"
              :key="dict.dictLabel"
              :label="dict.dictLabel"
              :value="dict.dictLabel" />
          </el-select>
        </el-form-item>

      </el-row>
      <el-row>
        <el-form-item label="邀请码"
          prop="customerNo">
          <el-input v-model="queryParams.customerNo"
            placeholder="请输入邀请码"
            clearable
            size="small"
            style="width: 232px;"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item style="margin-left: 20px;">
          <el-button type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh"
            size="mini"
            @click="resetQuery">重置</el-button>
        </el-form-item>

      </el-row>


    </el-form>

    <el-row class="row-mbinfo">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['customer:Info:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5" style="margin-left:10px">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['customer:Info:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5" style="margin-left:10px">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['customer:Info:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5" style="margin-left:10px">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['customer:Info:import']">导入</el-button>
      </el-col>

      <el-col :span="1.5" style="margin-left:10px">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['customer:Info:export']">导出
        </el-button>
      </el-col>
      -->
      <right-toolbar :showSearch.sync="showSearch"
        @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="divTable">
      <el-table border
        v-loading="loading"
        :data="InfoList"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange">
        <el-table-column label="会员ID"
          align="center"
          width="80"
          v-if="show"
          prop="customerUid" />
          <!--
        <el-table-column label="头像"
          align="center"
          prop="headImage">
          <template slot-scope="scope">
            <el-image style="border-radius:50px;"
              v-if="scope.row.headImage != null && scope.row.headImage != ''"
              slot="reference"
              :src="scope.row.headImage"
              class="image-rows"
              :preview-src-list="[scope.row.headImage]">
            </el-image>
          </template>
        </el-table-column>
        -->
        <el-table-column label="用户名称"
          align="center"
          prop="customerName"
          min-width="100" />
          <!--
        <el-table-column label="客户姓名"
          align="center"
          prop="contactMan"
          min-width="100" />
          -->
        <el-table-column label="邀请码"
          align="center"
          min-width="80"
          prop="customerNo" />

        <el-table-column label="手机号码"
          width="100"
          align="center"
          prop="phone">
          <template slot-scope="scope">
            <a style="color: #00AAFF;"
              @click="showPhone(scope.row)">
              {{ scope.row.phoneStr }}
            </a>
          </template>
        </el-table-column>
        <el-table-column label="会员等级"
          align="center"
          prop="levelName">
          <template slot-scope="scope">
            <a style="color: #00AAFF;"
              @click="levelHistory(scope.row.customerUid)">
              {{ scope.row.levelName }}
            </a>
          </template>
        </el-table-column>
        <el-table-column label="会员身份"
          align="center"
          min-width="120"
          prop="customerType" />
       <el-table-column label="身份详情"
         align="center"
         min-width="160"
         prop="realRemark" />

        <!-- <el-table-column label="详细地址" align="center" prop="addressDetail"/> -->
        <!--      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>-->
        <el-table-column label="客户状态"
          align="center"
          prop="status">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="注册时间"
          align="center"
          prop="createTime"
          width="180">

        </el-table-column>
        <el-table-column label="操作"
          align="center"
          width="100px"
          class-name="small-padding fixed-width"
          fixed="right">
          <template slot-scope="scope">
            <el-button size="mini"
              type="text"
              icon="el-icon-zoom-in"
              @click="handleShowDetail(scope.row)"
              v-hasPermi="['customer:Info:query']">查看
            </el-button>
            <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['customer:Info:edit']">修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-zoom-in" @click="handleShowAccount(scope.row)"
              v-hasPermi="['customer:Info:query']">账号信息
            </el-button>
            <el-button v-if="scope.row.accountStatus === '0'" size="mini" type="text" icon="el-icon-edit" @click="updateAccount(scope.row)"
                       v-hasPermi="['customer:Info:query']">启动账号
            </el-button> -->
            <!--            <el-button v-if="scope.row.accountStatus === '1'" size="mini" type="text" icon="el-icon-edit" @click="updateAccount(scope.row)"-->
            <!--                       v-hasPermi="['customer:Info:query']">锁定账号-->
            <!--            </el-button>-->
            <!-- <el-button  size="mini" type="text" icon="el-icon-zoom-in" @click="getQrCode(scope.row)"
                       v-hasPermi="['customer:Info:query']">查看二维码
            </el-button> -->
            <!-- <el-button size="mini" type="text" icon="el-icon-delete" v-if="scope.row.status == '0' "
              @click="handleDelete(scope.row)" v-hasPermi="['customer:Info:remove']">删除
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title"
      :visible.sync="open"
      width="700px"
      append-to-body>
      <el-form ref="form"
        :model="form"
        :rules="rules"
        label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="头像">
              <imageArraySize :imageStr.sync="form.headImage"
                :key="form.headImage"
                :width="100"
                :height="100"
                :size="1024"
                :limit="1"
                ref="childsss"></imageArraySize>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户名称"
              prop="customerName">
              <el-input v-model="form.customerName"
                placeholder="请输入客户名称"
                class="select-normal"
                show-word-limit
                maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="密码"
              prop="password">
              <el-input v-model="form.password"
                type="password"
                placeholder="请输入密码"
                class="select-normal" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-tooltip content="添加客户需输入账号密码,如不输入默认123456"
              placement="top">
              <i class="el-icon-question"
                style="margin-top: 10px; margin-left: 10px">
              </i>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="联系人"
              prop="contactMan">
              <el-input v-model="form.contactMan"
                placeholder="请输入联系人"
                class="select-normal"
                show-word-limit
                maxlength="10" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="性别"
              prop="sex">
              <el-radio v-model="form.sex"
                label="1">男</el-radio>
              <el-radio style="margin-left: 11%;"
                v-model="form.sex"
                label="0">女</el-radio>
              <!-- <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option v-for="dict in sexOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="手机号码"
              prop="phone">
              <el-input v-model="form.phone"
                placeholder="请输入手机号码"
                class="select-normal"
                show-word-limit
                maxlength="12" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="8">
            <el-form-item label="国籍" prop="nation">
              <el-input v-model="form.nation" placeholder="请输入国籍" />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="地址"
              prop="region">
              <el-cascader ref="cascaderAddr"
                v-model="form.region"
                style="width: 219px;"
                :options="options">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="详细地址"
              prop="addressDetail">
              <el-input v-model="form.addressDetail"
                placeholder="请输入详细地址"
                style="width: 500px;"
                class="select-normal"
                show-word-limit
                maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer"
        class="dialog-footer">
        <el-button type="primary"
          @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看客户等级历史记录 -->
    <el-dialog title="客户等级历史记录"
      :visible.sync="historyOpen"
      width="600px"
      append-to-body>
      <el-table :data="levelHistoryArr"
        v-loading="historyLoading"
        style="width: 100%">
        <!--        <el-table-column>-->
        <!--          <template slot-scope="scope">-->
        <!--            {{scope.$index+1}}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column prop="levelName"
          label="等级名称">
        </el-table-column>


        </el-table-column>
        <el-table-column prop="createTime"
          label="购买时间">
        </el-table-column>
      </el-table>
      <pagination v-show="historyTotal > 0"
        :total="historyTotal"
        :page.sync="historyQueryParams.pageNum"
        :limit.sync="historyQueryParams.pageSize"
        @pagination="levelHistory(levelHistoryArr[0].customerUid)" />
      <div slot="footer"
        class="dialog-footer">
        <el-button type="primary"
          @click="historySubmitForm">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 查看客户账号信息弹出框 -->
    <el-dialog title="客户账号信息"
      :visible.sync="accountOpen"
      width="762px"
      append-to-body>
      <el-table border
        :data="this.accountInfoArr"
        style="width: 100%">

        <el-table-column prop="accountName"
          label="登录账号"
          width="180">
        </el-table-column>
        <el-table-column prop="accountNickName"
          label="账号昵称"
          width="180">
        </el-table-column>
        <!-- <el-table-column prop="loginNumber" label="登录次数" width="180">
        </el-table-column> -->
        <el-table-column prop="sourcePort"
          label="账号来源端口"
          width="180"
          :formatter="accountSourcePort">

        </el-table-column>
        <el-table-column prop="accountStatus"
          label="状态"
          width="180">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.accountStatus"
              active-value="1"
              inactive-value="0"
              @change="handleaccountStatusChange(scope.row)"></el-switch>
            <!--            <span v-if="scope.row.accountStatus == 0">-->
            <!--              锁定-->
            <!--            </span>-->
            <!--            <span v-if="scope.row.accountStatus == 1">-->
            <!--              正常-->
            <!--            </span>-->
          </template>
        </el-table-column>
        <!--        <el-table-column label="操作" align="center" width="200px" class-name="small-padding fixed-width" fixed="right">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-button v-if="scope.row.accountStatus === '0'" size="mini" type="text" icon="el-icon-edit" @click="updateAccount(scope.row)"-->
        <!--                       v-hasPermi="['customer:Info:query']">启动-->
        <!--            </el-button>-->
        <!--            <el-button v-if="scope.row.accountStatus === '1'" size="mini" type="text" icon="el-icon-edit" @click="updateAccount(scope.row)"-->
        <!--                       v-hasPermi="['customer:Info:query']">锁定-->
        <!--            </el-button>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>

      <div slot="footer"
        class="dialog-footer">
        <el-button type="primary"
          @click="accountSubmitForm">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 查看客户信息对话框 -->
    <el-dialog :title="viewTitle"
      :visible.sync="viewOpen"
      width="700px"
      append-to-body>
      <infoDetail v-if="showData"
        :infoDetail="showData"></infoDetail>
    </el-dialog>

    <!-- 客户导入对话框 -->
    <el-dialog :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body>

      <el-upload ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?password=' + upload.password"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag>

        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>

        <div class="el-upload__tip"
          slot="tip">
          <el-input v-model="upload.password"
            type="password"
            placeholder="请输入密码" />
          <!--          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据-->
          <el-link type="info"
            style="font-size:12px"
            @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip"
          style="color:red"
          slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>

      <div slot="footer"
        class="dialog-footer">
        <el-button type="primary"
          @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!--   分享二维码弹框 -->
    <el-dialog title="分享二维码"
      :visible.sync="openShare"
      modal
      width="380px"
      append-to-body>

      <div style="display: flex;">
        <div class="divShare"
          align="center">
          <div class="shareSpan">
            小程序码
          </div>
          <el-image v-if="sharecustomerQrCode != null"
            style="width: 180px;height: 180px"
            :src="sharecustomerQrCode" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInfo,
  getInfo,
  delInfo,
  addInfo,
  updateInfo,
  updateCustomerStatus,
  updateAccountStatusById,
  getLevelInfoHistory,
  getCustomerAccount,
  updateAccountStatus,
  getSharecustomerQrCode
} from "@/api/customer/Info";
import {
  getRegion
} from '@/api/common/regin'
import imageArraySize from "@/components/ImageUpload/imageArraySize";
import {
  getToken
} from "@/utils/auth";
import log from "../../monitor/job/log";
import infoDetail from "@/components/Customer/infoDetail";
import {
  listLevel, listSelect
} from "@/api/customer/level";
//验证手机号
let checkPhone = (rule, value, callback) => {
  let reg =
    /^((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)$/
  if (!reg.test(value)) {
    callback(new Error('手机号或电话输入错误'))
  } else {
    callback()
  }
}
//验证密码
let password = (rule, value, callback) => {
  let reg = /^[0-9]{1,16}$/
  if (!reg.test(value) && value != null) {
    callback(new Error('请输入16为以内数字'))
  } else {
    callback()
  }
}
export default {
  name: "Info",
  components: {
    imageArraySize,
    infoDetail
  },
  data () {
    return {
      // 遮罩层
      loading: true,
      historyLoading: true,
      // 选中数组
      ids: [],
      //选中数组的名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 地区信息
      options: [],
      region: [],
      // 客户信息表格数据
      InfoList: [],
      // 弹出层标题
      title: "",
      //查看详细标题
      viewTitle: "",
      // 是否显示弹出层
      open: false,
      //是否显示查看详细弹出层
      viewOpen: false,
      //查看详细数据
      showData: [],
      // 性别 1男，0女字典
      sexOptions: [],
      //账号来源
      accountOptions: [],
      // 状态 1有效 0无效字典
      statusOptions: [],
      sfOptions: [],
      //等级信息数组
      LevelInfoArr: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        //账号密码
        password: "",
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/customer/Info/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        headImage: null,
        sex: null,
        nation: null,
        province: null,
        provinceCode: null,
        city: null,
        cityCode: null,
        area: null,
        areaCode: null,
        phone: null,
        r: null,
        f: null,
        m: null,
        rmfLabel: null,
        sort: null,

        contactMan: null,
        platformUid: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null,
        status: null,
        parentTree: null,
        fatherUid: null,
        grandFatherUid: null,
        customerType: null,
        addressDetail: null,
        region: [],
        levelUid: "",
        startBirthday: null,
        endBirthday: null,
        createTimeArr: []
      },
      rmfTags: [],
      rmfLabelTags: [],
      birthDayArr: [],
      historyQueryParams: {
        pageNum: 1,
        pageSize: 10,
        customerUid: null
      },
      historyTotal: 0,
      columns: [{
        label: '客户头像',
        dataIndex: 'headImage',
      },
      {
        label: '客户名称',
        dataIndex: 'customerName',
      },
      {
        label: '性别',
        dataIndex: 'sex',
      },
      {
        label: '国籍',
        dataIndex: 'nation',
      },
      {
        label: '省份',
        dataIndex: 'province',
      },
      {
        label: '城市',
        dataIndex: 'city',
      },
      {
        label: '区域',
        dataIndex: 'area',
      },
      {
        label: '详细地址',
        dataIndex: 'addressDetail',
      },
      {
        label: '手机号码',
        dataIndex: 'phone',
      },
      {
        label: '联系人',
        dataIndex: 'contactMan',
      },
      {
        label: '创建时间',
        dataIndex: 'createTime',
      },
      {
        label: '修改时间',
        dataIndex: 'updateTime',
      },
      {
        label: '创建人',
        dataIndex: 'createName',
      },
      {
        label: '修改人',
        dataIndex: 'updateName',
      }
      ],
      detailForm: {},
      // 表单参数
      form: {},
      show: false,
      // 表单校验
      rules: {
        customerName: [{
          required: true,
          message: "客户名称不能为空",
          trigger: "blur"
        }],
        sex: [{
          required: true,
          message: "性别不能为空",
          trigger: "blur"
        }],
        contactMan: [{
          required: true,
          message: "联系人不能为空",
          trigger: "blur"
        }],
        phone: [{
          required: true,
          message: "手机号码不能为空",
          trigger: "blur"
        },
        {
          type: 'number',
          validator: checkPhone,
          message: '输入有效手机号或电话',
          trigger: ['blur', 'change']
        }
        ],
        password: [
          {
            type: 'number',
            validator: password,
            message: '输入16位以内数字',
            trigger: ['blur', 'change']
          }
        ],
        region: [{
          required: true,
          message: "地址不能为空",
          trigger: "blur"
        }]
      },
      //省份数组
      provinceCodeArr: [],
      //城市数组
      cityCodeArr: [],
      //等级历史记录
      levelHistoryArr: [],
      //等级历史记录弹出框
      historyOpen: false,
      //客户账号信息
      accountInfoArr: [],
      //查看客户账号弹出框
      accountOpen: false,
      //分享者二维码
      sharecustomerQrCode: "",
      openShare: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
    };
  },

  created () {
    // if (!this.$route.query.hrefType) {
    //   let str = window.location.origin + this.$route.path + '&hrefType=blank';
    //   window.open(str)
    //   this.$store.dispatch("tagsView/delView", this.$route);
    //   this.$router.go(-1);
    //   // this.$router.push({
    //   //   path: "/index"
    //   // })
    //   return
    // }

    this.getList();
    this.getDicts("customer_sex").then(response => {
      this.sexOptions = response.data;
    });
    this.getDicts("customer_account_sourcePort").then(response => {
      this.accountOptions = response.data;
    });
    this.getDicts("sys_data_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("source_platform").then(response => {
      this.sfOptions = response.data;
    });

    this.getDicts("sys_rmf_value").then(response => {
      this.rmfTags = response.data;
    });
    this.getDicts("sys_customer_rmf").then(response => {
      this.rmfLabelTags = response.data;
    });
    //获取地区信息
    getRegion().then((response) => {
      response.data.forEach(item => {
        let province = new Object();
        province.value = item.value;
        province.label = item.label;
        this.provinceCodeArr.push(province);
        this.options = response.data
      })
    })
    //获取等级信息
    listSelect().then(response => {
      response.data.forEach(item => {
        let levelInfo = new Object();
        levelInfo.value = item.levelId;
        levelInfo.label = item.levelName;
        this.LevelInfoArr.push(levelInfo);
      })
    });
    let $this = this;
    var levelId = $this.$route.params && $this.$route.params.levelId;
    if (levelId != null) {
      this.queryParams.levelUid = parseInt(levelId);
      this.handleQuery();
    }
  },
  methods: {
    sortChange ({ column, prop, order }) {
      let val = ''
      if (prop == 'r') {
        val = 'r_value'
      } else if (prop == 'f') {
        val = 'f_value'
      } else {
        val = 'm_value'
      }
      this.queryParams.sort = val
      this.handleQuery();
    },
    //查看分享二维码
    getQrCode (row) {
      this.openShare = true;
      getSharecustomerQrCode(row.customerUid).then(response => {
        this.sharecustomerQrCode = response.data;
      });
    },
    //启动或锁定账号信息
    updateAccount (row) {
      updateAccountStatus(row).then(response => {
        this.msgSuccess("修改成功")
        this.getList();
      });
    },
    //等级历史记录
    levelHistory (customerUid) {
      this.historyLoading = true;
      this.levelHistoryArr = [];
      getLevelInfoHistory(this.historyQueryParams, customerUid).then(response => {
        this.historyLoading = false;
        this.levelHistoryArr = response.rows;
        this.historyOpen = true;
        this.historyTotal = response.total;
      });
    },
    historySubmitForm () {
      this.historyOpen = false;
    },
    //显示隐藏手机号
    showPhone (row) {
      row.PhoneUpdate = row.phone;
      if (row.phoneStr.indexOf("*") != -1 == false) {
        row.PhoneUpdate = row.phoneStr;
        var len = row.phone.length - 3 - 4;
        var xing = '';
        for (var i = 0; i < len; i++) {
          xing += "*";
        }
        row.phoneStr = row.phone.substring(0, 3) + xing + row.phone.substring(row.phone.length - 4)
      } else {
        row.phoneStr = row.PhoneUpdate;
      }
    },
    //选择城市
    provinceChanage (val) {
      this.queryParams.cityCode = null;
      this.cityCodeArr = [];
      this.options.forEach(item => {
        if (val == item.value) {
          item.children.forEach(childrenItem => {
            let city = new Object();
            city.value = childrenItem.value;
            city.label = childrenItem.label;
            this.cityCodeArr.push(city);
          })
        }
      })
    },
    /** 查询客户信息列表 */
    getList () {
      this.loading = true;
      if (this.birthDayArr && this.birthDayArr.length > 0) {
        this.queryParams.startBirthday = this.birthDayArr[0]
        this.queryParams.endBirthday = this.birthDayArr[1]
      } else {
        this.queryParams.startBirthday = null
        this.queryParams.endBirthday = null
      }

      listInfo(this.queryParams).then(response => {
        this.InfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 性别 1男，0女字典翻译
    sexFormat (row, column) {
      return this.selectDictLabel(this.sexOptions, row.sex);
    },
    accountSourcePort (row, column) {
      return this.selectDictLabel(this.accountOptions, row.sourcePort);
    },
    // 状态 1有效 0无效字典翻译
    statusFormat (row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        customerUid: null,
        customerName: null,
        headImage: null,
        sex: null,
        nation: null,
        province: null,
        provinceCode: null,
        city: null,
        cityCode: null,
        area: null,
        areaCode: null,
        phone: null,
        contactMan: null,
        platformUid: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null,
        status: "0",
        parentTree: null,
        fatherUid: null,
        grandFatherUid: null,
        customerType: null,
        addressDetail: null
      };
      this.birthDayArr = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.birthDayArr = []
      this.queryParams.sort = null
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.customerUid)
      this.names = selection.map(item => item.customerName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      //用于禁用删除
      if (this.multiple == false) {
        for (var i = 0; i < selection.length; i++) {
          var element = selection[i];
          if ("1" === element.status) {
            this.multiple = true;
            break;
          }
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd () {
      //获取地区信息
      getRegion().then((response) => {
        this.options = response.data
      })
      this.reset();
      this.open = true;
      this.title = "添加客户信息";
    },
    // 状态修改
    handleStatusChange (row) {
      let text = row.status === "0" ? "无效" : "有效";
      this.$confirm('确定要把"' + row.customerName + '"设为' + text + '吗？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return updateCustomerStatus(row.customerUid, row.status);
      }).then(() => {
        this.msgSuccess("操作成功");
        this.getList();
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    //账号状态修改
    handleaccountStatusChange (row) {
      let text = row.accountStatus === "0" ? "锁定" : "启动";
      this.$confirm('确定要' + text + '账号吗？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        // if(row.accountStatus === '0'){
        //   row.accountStatus = '1';
        // }else {
        //   row.accountStatus = '0';
        // }
        return updateAccountStatusById(row.customerAccountUid, row.accountStatus);
      }).then(() => {
        this.msgSuccess("操作成功");
        this.handleShowAccount(row);
      }).catch(function () {
        row.accountStatus = row.accountStatus === "0" ? "1" : "0";
      });
    },
    // 查看账号信息
    handleShowAccount (row) {
      getCustomerAccount(row.customerUid).then(response => {
        this.accountInfoArr = response.rows;
        this.accountOpen = true;
      });
    },
    //查看账号信息关闭
    accountSubmitForm () {
      this.accountOpen = false;
    },
    /** 查看详情按钮操作 **/
    handleShowDetail (row) {
      this.$router.push("/customer/detail/" + row.customerUid);
    },
    handCloseDetail () {
      this.viewOpen = false
      this.showData = []
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const customerUid = row.customerUid || this.ids
      getInfo(customerUid).then(response => {
        this.form = response.data.customer;
        this.open = true;
        this.title = "修改客户信息";
        //获取地区信息
        getRegion().then((response) => {
          this.options = response.data
        })
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs.childsss.selectImgShare();
      this.$refs["form"].validate(valid => {
        console.log(this.form)
        let areaName = this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels;
        this.form.area = areaName[2];
        this.form.city = areaName[1];
        this.form.province = areaName[0];
        let area = this.$refs['cascaderAddr'].getCheckedNodes()[0].path
        this.form.provinceCode = area[0];
        this.form.cityCode = area[1];
        this.form.areaCode = area[2];
        if (valid) {
          if (this.form.customerUid != null) {
            console.log(this.form);
            updateInfo(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const customerUids = row.customerUid || this.ids;
      const customernames = row.customerName || this.names;
      this.$confirm('是否确认删除客户信息名称为"' + customernames + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delInfo(customerUids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('customer/Info/export', {
        ...this.queryParams
      }, `customer_Info.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport () {
      this.upload.title = "客户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate () {
      this.download('customer/Info/importTemplate', {
        ...this.queryParams
      }, `客户信息模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {
        dangerouslyUseHTMLString: true
      });
      this.getList();
    },
    // 提交上传文件
    submitFileForm () {
      if (this.upload.password != null && this.upload.password != "") {
        this.$refs.upload.submit();
      } else {
        this.msgError("请输入密码");
      }
    }
  }
};
</script>

<style scoped>
.divShare {
  width: 200px;
  height: 240px;
  display: inline-block;
  background-color: #f5f5f5;
  margin: 5px 60px;
}

.shareSpan {
  font-size: 16px;
  font-weight: 600;
  width: 200px;
  margin-bottom: 10px;
  margin-top: 10px;
}
</style>
